<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col
            :md="6"
            :sm="24">
            <a-form-item label="资源名称">
              <a-input
                v-model="queryParam.dto.fileName"
                placeholder="" />
            </a-form-item>
          </a-col>
          <a-col
            :md="6"
            :sm="24">
            <span
              class="table-page-search-submitButtons"
              :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button
                type="primary"
                @click="search(1)">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="search(2)">重置</a-button>
              <a-divider type="vertical"/>
              <a-button
                style="margin-left: 8px"
                @click="addGroup">新建</a-button>

              <a-button
                style="margin-left: 8px"
                @click="managerGroup">管理</a-button>

              <a-button
                type="primary"
                style="margin-left: 8px"
                @click="uploadFile">上传资源</a-button>
            </span>
          </a-col>
        </a-row>

      </a-form>
    </div>

    <div v-if="groups.length>0">
      <a-button
        @click="setQueryParam(group.id,index)"
        :key="index"
        v-for="(group,index) in groups"
        :class="activeClass ==index?'selectBton':''"
        style="margin-left: 10px;margin-bottom: 5px ;"
        type="round"
        icon="search">
        {{ group.name }}({{ group.fileCount }})</a-button>
    </div>

    <a-divider />

    <a-row >
      <a-col :md="6" :sm="24" v-for="(data,index) in datas" :key="index">
        <a-card hoverable >
          <img
            v-if="!isVideo(data.fileType)"
            alt="example"
            :src="coverFileCover(data.fileFullPath,data.fileType)"
            style="width:54%;height:230px;object-fit: cover;overflow-y: hidden;margin-left: 22%;"
            slot="cover"
          />
          <video style="width:100%;height:225px;object-fit: fill;overflow-y: hidden" loop="loop" autoplay="autoplay" :src="data.fileFullPath" v-if="isVideo(data.fileType)"/>
          <template class="ant-card-actions" slot="actions">

            <a-popconfirm
              title="确定要删除该文件吗？"
              @confirm="deleteFile(data.fileUid)"
              okText="确认"
              cancelText="取消">
              <span v-action:resource:del><a-icon type="delete" /></span>
            </a-popconfirm>

            <a-tooltip>
              <template slot="title">
                复制标题
              </template>
              <a-icon type="copy" @click="copyIt(data.fileName)"/>
            </a-tooltip>

            <a-tooltip>
              <template slot="title">
                复制链接
              </template>
              <a-icon type="copy" @click="copyIt(data.fileFullPath)"/>
            </a-tooltip>

            <a-tooltip>
              <template slot="title">
                下载文件
              </template>
              <a-icon type="arrow-down" @click="downIt(data.id)"/>
            </a-tooltip>
          </template>

          <a-card-meta :title="data.fileName" :description="'大小:'+conver(data.fileSize)+' 日期:'+converDate(data.gmtCreate)">
            <!-- <a-avatar
            slot="avatar"
            src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"
          /> -->
          </a-card-meta>
        </a-card>
        <a-divider type="horizontal" :dashed="true"/>
      </a-col>
    </a-row>

    <add-handle ref="addHandle" @ok="loadData"></add-handle>
    <manager-handle ref="managerHandle" @ok="loadData"></manager-handle>
    <simple-vue-upload ref="uploaderSimple" @uploadOk="uploadOk" />

    <a-pagination :current="queryParam.pageNo" :pageSize="queryParam.pageSize" :total="total" @change="loadChange" v-if="datas.length>0"/>

  </a-card>

</template>

<script>
import moment from 'moment'
import { pageMedia, deleteFile, listGroup, updateFileGid, downFile } from '@/api/site/upFile'
import { STable } from '@/components'
import addHandle from './addHandle'
import managerHandle from './managerHandle'
import SimpleVueUpload from '@/components/SimpleVueUpload/SimpleVueUpload.vue'
export default {
  name: 'TableList',
  components: {
    STable,
    addHandle,
    managerHandle,
    SimpleVueUpload
  },
  props: {
    statusFilter: {
      type: Function,
      default: undefined
    }
  },
  data () {
    return {
      mdl: {},
      advanced: false,
      queryParam: {
        dto: {
        },
        pageNo: 1,
        pageSize: 12
      },
      datas: [],
      total: 0,
      fileGroupId: null,
      activeClass: 0,
      groups: [],
      video: []
    }
  },
  created () {
    this.loadData(this.queryParam)
  },
  methods: {
    handleOk () {
      this.loadData()
    },
    search (type) {
       this.queryParam.pageNo = 1
       if (type === 2) {
          this.queryParam.dto.fileName = null
          this.queryParam.dto.fileGroupId = '-1'
          this.fileGroupId = null
          this.activeClass = 0
       }
       this.loadData()
    },
    loadChange (page, pageSize) {
       this.queryParam.pageNo = page
       this.loadData()
    },
    copyIt (content) {
          const input = document.createElement('input')
          document.body.appendChild(input)
          input.setAttribute('value', content)
          input.select()
          if (document.execCommand('copy')) {
              document.execCommand('copy')
              this.$message.info('复制成功!')
          }
          document.body.removeChild(input)
    },
    setQueryParam (fileGroupId, index) {
      this.fileGroupId = fileGroupId
      this.activeClass = index
      this.queryParam.dto.fileGroupId = fileGroupId
      this.loadData()
    },
    loadData () {
      pageMedia(this.queryParam).then(response => {
        if (response.code === 0) {
          this.total = response.res.total
          this.datas = response.res.rows
        }
      })

      listGroup({}).then(response => {
        this.groups = response.res
         console.log(response)
      })
    },
    uploadFile () {
       this.$refs['uploaderSimple'].openUpload(false)
    },
    uploadOk (files) {
      if (files.code === 0) {
         const id = files.res.id
         updateFileGid({ fileId: id, gid: this.fileGroupId }).then(response => {
            if (response.code === 0) {
               this.loadData()
            }
         })
      }
       console.log(files)
    },
    downIt (id) {
      downFile({ id: id }).then(response => {
        const blob = new Blob([response.data])
        const linkNode = document.createElement('a')
        linkNode.download = response.headers.filename // a标签的download属性规定下载文件的名称
        linkNode.style.display = 'none'
        linkNode.href = URL.createObjectURL(blob) // 生成一个Blob URL
        document.body.appendChild(linkNode)
        linkNode.click() // 模拟在按钮上的一次鼠标单击
        URL.revokeObjectURL(linkNode.href) // 释放URL 对象
        document.body.removeChild(linkNode)
      })
    },
    addGroup () {
      this.$refs.addHandle.add()
    },
    deleteFile (fileUid) {
      deleteFile({ fileUid: fileUid }).then(response => {
        if (response.code === 0) {
           this.$message.info('删除成功!')
           this.loadData()
        } else {
          this.$message.error(response.msg)
        }
      })
    },
    coverFileCover (fileFullPath, fileType) {
       let cover = '/default_file.png'
       if (fileFullPath && fileType) {
          const images = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff', 'jfif']
          if (images.indexOf(fileType) >= 0) {
            cover = fileFullPath
          }
       }
       return cover
    },
    isVideo (fileType) {
      if (fileType) {
        const videos = ['avi', 'rmvb', 'flv', 'mkv', 'mp4', '3gp', 'asf', 'f4v', 'qsv', 'hddvd', 'ogv']
        return videos.indexOf(fileType) >= 0
      } else {
        return false
      }
    },
    managerGroup () {
         this.$refs.managerHandle.show()
    },
    converDate (date) {
      return moment(date).format('YYYY-MM-DD')
    },
    conver (limit) {
            if (!limit) {
              return '未知'
            }
            var size = ''
            if (limit < 0.1 * 1024) { // 如果小于0.1KB转化成B
                size = limit.toFixed(2) + 'B'
            } else if (limit < 0.1 * 1024 * 1024) { // 如果小于0.1MB转化成KB
                size = (limit / 1024).toFixed(2) + 'KB'
            } else if (limit < 0.1 * 1024 * 1024 * 1024) { // 如果小于0.1GB转化成MB
                size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
            } else { // 其他转化成GB
                size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
            }

            var sizestr = size + ''
            var len = sizestr.indexOf('\\.')
            var dec = sizestr.substr(len + 1, 2)
            if (dec === '00') { // 当小数点后为00时 去掉小数部分
                return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
            }
            return sizestr
    },
    resetSearchForm () {
      alert(11)
      this.queryParam = {
        dto: { fileGroupId: '-1' },
        pageNo: 1,
        pageSize: 12
      }
      this.handleOk()
    }
  }
}
</script>
<style>
  .selectBton{
   color:red!important
  }
</style>
